import datetime

from sqlalchemy.orm import joinedload_all

from database import db
from ..models.ticket import  Ticket
from ..models.offer import Offer


class OfferService(object):
    @classmethod
    def get_offer_by_product(cls, product):
        query = Offer.query.order_by(Offer.price)

        data = query.filter(Offer.product_id == product.id) \
            .filter(Offer.status != 'removed') \
            .options(
            # joinedload_all(
            #     Offer.product
            # ),
            joinedload_all(
                Offer.dealer
            )
        ).all()

        return data

    @classmethod
    def get_offer_by_id(cls,offer_id):
        return Offer.query.filter(Offer.id == offer_id).first()

    @classmethod
    def create_offer(cls,product_id, count, dealer_id, price, mask, **kwargs):
        kwargs.update({
            'product_id': product_id,
            'status': 'normal',
            'slug': 'cdk',
            'dealer_id': dealer_id,
            'price': price,
            'count': count,
            'updated_at': datetime.datetime.now(),
            'created_at': datetime.datetime.now(),
            'mask': mask
        })
        offer = Offer(**kwargs)
        db.session.add(offer)
        db.session.commit()
        return offer.id

    @classmethod
    def create_ticket(cls,offer_id, value, **kwargs):
        kwargs.update(
            {
                'offer_id': offer_id,
                'value':value,
                'status': 'normal',
                'update_at': datetime.datetime.now(),
                'created_at': datetime.datetime.now()
            }
        )
        ticket = Ticket(**kwargs)
        db.session.add(ticket)
        db.session.commit()
        return Offer.query.filter(Offer.id == offer_id).filter(Offer.status == Offer.STATUS_NORMAL).first()
